<?php
namespace app\admin\controller;
use app\admin\model\{StoreCoupon,Goods,StoreCategory,StoreCouponIssue};
use  think\facade\Db;

class CouponTemplate extends Base{
    

    /**
     * 首页
     */
    public function index(){
        if(IS_POST) {
            $search  = request()->param();
            $where = [];
            $where[] = ['is_del','=',0];
            if(isset($search["name"]) && $search["name"]!="") $where[] = ["name","=",$search["name"]];
            $db   = StoreCoupon::where($where)->order('id desc');
            $list = $db->limit(paginator())->append(['type_name'])->select();
             if(count($list)){
                foreach($list as &$v){
                    $v["thumb"] = table_img($v["thumb"]);
                    $v['add_time'] = date('Y-m-d H:i',$v['add_time']);
                    if($v['status'] ==1){
                        $v['valid'] = '有效';
                    }else{
                        $v['valid'] = '<span style="color:red">无效</span>';
                    }
                }
            }
            admin_response(0, 'success', $list, $db->count());
        }
        return $this->render_table([
           "page"=>true,
            "toolbar" => [table_button('admin/CouponTemplate/create',"添加","frame",'',['800px','650px'])],
            "toolbar_row" => [ 
                    table_button('admin/CouponTemplate/edit',"编辑","frame",'',['800px','650px']),
                    table_button('admin/CouponTemplate/delete',"删除","confirm",'确认删除么，请谨慎操作',['800px','650px']),
                     table_button('admin/CouponTemplate/issue',"发布","frame",'',['800px','650px']),
                    ],

            "cols" => [ 
                    ["type"=>"checkbox"],
                    ["field"=>"title", "title"=>"名称","align"=>"center"],
                    ["field"=>"type_name", "title"=>"分类","align"=>"center"],
                    ["field"=>"coupon_price", "title"=>"优惠券面值","align"=>"center"],
                    ["field"=>"use_min_price", "title"=>"优惠券最低消费","align"=>"center"],
                    ["field"=>"coupon_time", "title"=>"有效期","align"=>"center"],
                    ["field"=>"valid", "title"=>"是否有效","align"=>"center"],
                    ["field"=>"add_time", "title"=>"添加时间","align"=>"center"],

            ],
            "where"=>[
                    "name"=>["type"=>"input","title"=>"名称"],

            ]

            ],false);

    }


    /**
     * 添加优惠券
     * @return [type] [description]
     */
    public function create(){
        if(request()->isPost()) {
           $data = request()->post();
           $data['add_time']  = time();
           if(StoreCoupon::create($data)) json_response(1,'操作成功');
           json_response(0,'操作失败');
        }else{
            $cates = sort_list_tier(StoreCategory::field('id,pid,cate_name')->select()->toArray());
            $goods = Goods::where('is_del',0)->field('id as value,store_name as name')->select()->toArray();
            $goods_select = json_encode($goods);
            $this->assign(compact('cates','goods_select'));
            return $this->fetch();
        }
    }



    /**
     * 编辑
     * @return void
     * @author 
     * date 
     */
    public function edit(){
        $id = \param_check('id');
        if(request()->isPost()) {
           $data = request()->post();
           if(StoreCoupon::update($data,['id'=>$id])) json_response(1,'操作成功');
           json_response(0,'操作失败');
        }else{
            $info = StoreCoupon::find($id);
            $cates = sort_list_tier(StoreCategory::field('id,pid,cate_name')->select()->toArray());
            $goods = Goods::where('is_del',0)->field('id as value,store_name as name')->select()->toArray();
            $goods_select = json_encode($goods);
            $this->assign(compact('cates','goods_select','info'));
            return $this->fetch();
        }
    }





        /**
     * 删除
     * @return void
     * @author Sam
     * date 2021-07-01
     */
    public function delete(){
        $id = param_check('id');
        if(!$StoreCoupon = StoreCoupon::get($id)) json_response(0,'不存在');
        $StoreCoupon->is_del = 1;
        if($StoreCoupon->save()) json_response(1,'操作成功');
        json_response(0,'操作失败');
    }

    /**
     * 发布
     * @return [type] [description]
     */
    public function issue(){
        $id = param_check('id');
        if(request()->isPost()) {
            $data = request()->post();
            Db::startTrans();
            try {
                if(strtotime($data['end_time']) <= strtotime($data['start_time']))  exception('结束时间不得小于开始时间');
                if($data['is_permanent'] == 0 && $data['total_count']<=0)           exception('请输入发布数量');
                if($data['is_full_give'] == 1 && $data['full_reduction']<=0)        exception('请输入满赠金额');
                $data['start_time']      = strtotime($data['start_time']);
                $data['end_time']        = strtotime($data['end_time']);
                $data['add_time']        = time();
                $res = StoreCouponIssue::setIssue($id, $data['total_count'], $data['start_time'],$data['end_time'], $data['total_count'], $data['status'], $data['is_permanent'],$data['full_reduction'], $data['is_full_give']);
                if($data['to_people'] && $data['to_people'] !='' && !StoreCouponIssue::send_coupons_by_txt($data['to_people'],$res->id)){
                    \exception(StoreCouponIssue::getErrorInfo());
                } 
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                json_response(0,$e->getMessage());
            }
            json_response(1,'操作成功');
         }else{
            $info = StoreCoupon::find($id);
            $option = StoreCoupon::where('is_del',0)->field('id as value,title')->select();
            return $this->render_form([
                ['type'=>'text', 'name'=>'title', 'title'=>'优惠券','option'=>$option,'readonly'=>true],
                ['type'=>'text','text_type'=>'datetime','name'=>'start_time', 'title'=>'开始时间','readonly'=>true],
                ['type'=>'text','text_type'=>'datetime','name'=>'end_time', 'title'=>'结束时间','readonly'=>true],
                [
                    ['type'=>'radio','name'=>'is_permanent', 'title'=>'是否限量','option'=>[
                    ['title'=>'限量','value'=>0],
                    ['title'=>'不限量','value'=>1]
                ]],
                ['type'=>'text','text_type'=>'number','name'=>'total_count', 'title'=>'发布数量'],
                ],
                [
                    ['type'=>'radio','name'=>'is_full_give', 'title'=>'消费满赠','option'=>[
                    ['title'=>'关闭','value'=>0],
                    ['title'=>'开启 ','value'=>1],
                ]],
                ['type'=>'text','text_type'=>'number','name'=>'full_reduction', 'title'=>'满赠金额'],
                ],
                ['type'=>'upload','upload_type'=>'file','name'=>'to_people', 'title'=>'指定人员发放','remark'=>'上传txt文件指定人员发放，输入用户手机号，一行一个。第一行为空'],
                ['type'=>'radio','name'=>'status', 'title'=>'状态','option'=>[
                    ['title'=>'开启 ','value'=>1],
                    ['title'=>'关闭','value'=>0]
                ]],
            ],$info);
         }
    }


}